package com.wy._06QRCode;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

public class Generate {
    public static void main(String[] args) {
        createORImage();
    }
    static Random random = new Random();

    public static void createORImage() {
        int width = 500;
        int height = 500;
        int[][] twoDimensionalArray = createTwoDimensionalArray(50);

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        // 设置背景颜色为蓝色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

//        开始画
        int length = twoDimensionalArray.length;
        int  latticeUnit  = width/ length;

        for (int i = 0; i <length; i++) {
            for (int j = 0; j < twoDimensionalArray[i].length; j++) {
                if (twoDimensionalArray[i][j]==0){
                    g.setColor(Color.WHITE);
                }else {
                    g.setColor(Color.BLACK);
                }
                g.fillRect(j*latticeUnit, i*latticeUnit, latticeUnit, latticeUnit);
            }
        }
        g.dispose();

        try {
            File output = new File("src/main/resources/generated_image.png");
            ImageIO.write(image, "png", output);
            System.out.println("图片已生成到 generated_image.png");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param length: 二维数组的长度
     * @return 二维数组
     */
    public static int[][] createTwoDimensionalArray(int length) {
        int[][] arr = new int[length][length];
        for (int i = 0; i < arr.length; i++) {
            for (int i1 = 0; i1 < arr[i].length; i1++) {
                arr[i][i1] = random.nextInt(2);
            }
        }
        for (int[] ints : arr) {
            for (int anInt : ints) {
                System.out.print(anInt);
            }
            System.out.println();
        }
        return arr;
    }
}